package com.wmz.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wmz.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wmz
 * @date 2024/7/6 17:07
 * @description feign拦截器
 * 处理：token传递
 * 浏览器 -> A服务 -> B服务
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     *
     * @param requestTemplate 即将要发起的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(ObjectUtils.isNotNull(requestTemplate)) {
            //获取当前请求
            HttpServletRequest request = requestAttributes.getRequest();
            //判断是否有值
            if(ObjectUtils.isNotNull(request)) {
                //获取当前请求头中的token值，传递给下一个请求对象的请求头中
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION,authorization);
                return;
            }
            //用来处理不是从浏览器发出的请求，比如说：定时任务，消息队列等
            requestTemplate.header(AuthConstants.AUTHORIZATION,AuthConstants.BEARER + "20684fee-fd79-4a6f-ade0-ed3327cf79d8");
        }
    }
}
